#include "err.hpp"
#include <iostream>
#include <cstring>
#include <string>
#include <pthread.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void *recv(void *args)
{
    int sock = *(static_cast<int *>(args));
    char buffer[1024];
    sockaddr_in temp;
    socklen_t len = sizeof(temp);

    while (true)
    {
        int n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&temp, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "请输入程序名 + 对方ip + 对方端口号" << std::endl;
        exit(USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(SOCKED_ERR);
    }
    // 系统在我们第一次调用系统调用发送的时候，会自动给我绑定ip和端口号

    // 填充server的信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));

    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    //
    pthread_t r_id;
    pthread_create(&r_id, nullptr, recv, (void*)&sock);

    while(true)
    {
        std::string message;
        std::cout << "请输入..." << std::endl;
        getline(std::cin,message);

        sendto(sock,message.c_str(),message.size(),0,(sockaddr*)&server,sizeof(server));
    }

    pthread_join(r_id,nullptr);

    return 0;
}



